#include "FormatQualifier.h"
#include <boost/algorithm/string/trim.hpp>

FormatQualifier::FormatQualifier(const std::map<std::string, std::string>& formats) :
                formats_(formats) { } 

std::string FormatQualifier::getFormat(const std::string& filename) const {
    
    std::string cmd = BASE_CMD;
    cmd.append(filename);

    return normalizeFormat(exec(cmd));
}

std::string FormatQualifier::exec(const std::string& cmd) const {

    FILE* pipe = popen(cmd.c_str(), "r");
    if (!pipe) return ERR_CODE;
    char buffer[BUFFER_SIZE];
    std::string result;

    while(!feof(pipe)) {
        if(fgets(buffer, BUFFER_SIZE, pipe) != nullptr) {
            result += buffer;
        }
    }
    pclose(pipe);
    return result;
}

std::string FormatQualifier::getMimeType(const std::string& fmt) const {
    if (formats_.find(fmt) == formats_.end()) {
        return "";
    }
    return formats_.at(fmt);
}

std::string FormatQualifier::normalizeFormat(const std::string& fmtstring) const {
    auto fmt = fmtstring;
    boost::algorithm::trim(fmt);
    return fmt;
}
